<script setup lang="ts">
import { reactive, ref, h } from 'vue';
import { NButton, NPopconfirm, NSpace, NTag } from 'naive-ui';
import { fetchScreenList, deleteScreen, publishScreen, offlineScreen } from '@/service/api';
import { useBoolean } from '@sa/hooks';
import { $t } from '@/locales';
import ScreenOperateDrawer from './modules/screen-operate-drawer.vue';
import ScreenDesignerModal from './modules/screen-designer-modal.vue';
import ScreenPreviewModal from './modules/screen-preview-modal.vue';

const { bool: visible, setTrue: openModal } = useBoolean();
const { bool: designerVisible, setTrue: openDesigner, setFalse: closeDesigner } = useBoolean();
const { bool: previewVisible, setTrue: openPreview, setFalse: closePreview } = useBoolean();

const queryParams = reactive({
  name: '',
  screenType: '',
  status: '',
  projectId: undefined as number | undefined,
  pageNum: 1,
  pageSize: 10
});

const tableData = ref<Api.Dataplatform.Screen[]>([]);
const loading = ref(false);
const total = ref(0);
const operateType = ref<'add' | 'edit'>('add');
const editingData = ref<Api.Dataplatform.Screen | null>(null);
const currentScreenId = ref<number | null>(null);

const screenTypeOptions = [
  { label: '自定义', value: 'CUSTOM' },
  { label: '模板', value: 'TEMPLATE' }
];

const statusOptions = [
  { label: '草稿', value: 'DRAFT' },
  { label: '已发布', value: 'PUBLISHED' },
  { label: '已下线', value: 'OFFLINE' }
];

const columns = [
  { type: 'selection', width: 50, fixed: 'left' },
  { title: 'ID', key: 'id', width: 80, ellipsis: { tooltip: true } },
  { title: '大屏名称', key: 'name', width: 200, ellipsis: { tooltip: true } },
  {
    title: '大屏类型',
    key: 'screenType',
    width: 120,
    render: (row: Api.Dataplatform.Screen) => {
      const typeMap: Record<string, { label: string; type: 'success' | 'info' }> = {
        CUSTOM: { label: '自定义', type: 'info' },
        TEMPLATE: { label: '模板', type: 'success' }
      };
      const config = typeMap[row.screenType] || { label: row.screenType, type: 'info' };
      return h(NTag, { type: config.type }, () => config.label);
    }
  },
  {
    title: '尺寸',
    key: 'size',
    width: 150,
    render: (row: Api.Dataplatform.Screen) => `${row.width} × ${row.height}`
  },
  {
    title: '刷新间隔',
    key: 'refreshInterval',
    width: 120,
    render: (row: Api.Dataplatform.Screen) => (row.refreshInterval > 0 ? `${row.refreshInterval}秒` : '不刷新')
  },
  {
    title: '状态',
    key: 'status',
    width: 100,
    render: (row: Api.Dataplatform.Screen) => {
      const statusMap: Record<string, { label: string; type: 'default' | 'success' | 'warning' }> = {
        DRAFT: { label: '草稿', type: 'default' },
        PUBLISHED: { label: '已发布', type: 'success' },
        OFFLINE: { label: '已下线', type: 'warning' }
      };
      const config = statusMap[row.status] || { label: row.status, type: 'default' };
      return h(NTag, { type: config.type }, () => config.label);
    }
  },
  { title: '描述', key: 'description', width: 200, ellipsis: { tooltip: true } },
  { title: '创建时间', key: 'createTime', width: 180 },
  {
    title: '操作',
    key: 'actions',
    width: 300,
    fixed: 'right',
    render: (row: Api.Dataplatform.Screen) => {
      return h(NSpace, {}, () => [
        h(NButton, { size: 'small', onClick: () => handleDesign(row) }, () => '设计'),
        h(NButton, { size: 'small', onClick: () => handlePreview(row) }, () => '预览'),
        h(NButton, { size: 'small', onClick: () => handleEdit(row) }, () => '编辑'),
        row.status === 'DRAFT' && h(NPopconfirm, { 
          onPositiveClick: () => handlePublish(row.id) 
        }, {
          default: () => '确认发布此大屏吗？',
          trigger: () => h(NButton, { size: 'small', type: 'success' }, () => '发布')
        }),
        row.status === 'PUBLISHED' && h(NPopconfirm, { 
          onPositiveClick: () => handleOffline(row.id) 
        }, {
          default: () => '确认下线此大屏吗？',
          trigger: () => h(NButton, { size: 'small', type: 'warning' }, () => '下线')
        }),
        h(NPopconfirm, { 
          onPositiveClick: () => handleDelete(row.id) 
        }, {
          default: () => '确认删除此大屏吗？',
          trigger: () => h(NButton, { size: 'small', type: 'error' }, () => '删除')
        })
      ].filter(Boolean));
    }
  }
];

async function getTableData() {
  loading.value = true;
  try {
    const { data } = await fetchScreenList(queryParams);
    if (data) {
      tableData.value = data.rows || [];
      total.value = data.total || 0;
    }
  } finally {
    loading.value = false;
  }
}

function handleQuery() {
  queryParams.pageNum = 1;
  getTableData();
}

function handleReset() {
  Object.assign(queryParams, {
    name: '',
    screenType: '',
    status: '',
    projectId: undefined,
    pageNum: 1,
    pageSize: 10
  });
  getTableData();
}

function handleAdd() {
  operateType.value = 'add';
  editingData.value = null;
  openModal();
}

function handleEdit(row: Api.Dataplatform.Screen) {
  operateType.value = 'edit';
  editingData.value = row;
  openModal();
}

function handleDesign(row: Api.Dataplatform.Screen) {
  currentScreenId.value = row.id;
  openDesigner();
}

function handlePreview(row: Api.Dataplatform.Screen) {
  currentScreenId.value = row.id;
  openPreview();
}

async function handlePublish(id: number) {
  await publishScreen(id);
  window.$message?.success('发布成功');
  getTableData();
}

async function handleOffline(id: number) {
  await offlineScreen(id);
  window.$message?.success('下线成功');
  getTableData();
}

async function handleDelete(id: number) {
  await deleteScreen([id]);
  window.$message?.success('删除成功');
  getTableData();
}

function handlePageChange(page: number) {
  queryParams.pageNum = page;
  getTableData();
}

function handlePageSizeChange(pageSize: number) {
  queryParams.pageSize = pageSize;
  queryParams.pageNum = 1;
  getTableData();
}

function init() {
  getTableData();
}

init();
</script>

<template>
  <div class="h-full flex-col-stretch gap-16px overflow-hidden lt-sm:overflow-auto">
    <NCard :title="$t('page.dataplatform.screen.title')" :bordered="false" size="small" class="sm:flex-1-hidden card-wrapper">
      <template #header-extra>
        <NButton type="primary" size="small" @click="handleAdd">
          <icon-ic-round-plus class="mr-4px text-20px" />
          新增大屏
        </NButton>
      </template>

      <div class="h-full flex-col">
        <NSpace class="pb-12px" justify="space-between">
          <NSpace>
            <NInput v-model:value="queryParams.name" placeholder="大屏名称" clearable class="w-200px" />
            <NSelect
              v-model:value="queryParams.screenType"
              placeholder="大屏类型"
              clearable
              :options="screenTypeOptions"
              class="w-150px"
            />
            <NSelect
              v-model:value="queryParams.status"
              placeholder="状态"
              clearable
              :options="statusOptions"
              class="w-150px"
            />
          </NSpace>
          <NSpace>
            <NButton size="small" type="primary" @click="handleQuery">
              <icon-ic-round-search class="mr-4px text-16px" />
              查询
            </NButton>
            <NButton size="small" @click="handleReset">
              <icon-ic-round-refresh class="mr-4px text-16px" />
              重置
            </NButton>
          </NSpace>
        </NSpace>

        <NDataTable
          :columns="columns"
          :data="tableData"
          :loading="loading"
          :scroll-x="1400"
          :pagination="{
            page: queryParams.pageNum,
            pageSize: queryParams.pageSize,
            itemCount: total,
            showSizePicker: true,
            pageSizes: [10, 20, 50, 100],
            onUpdatePage: handlePageChange,
            onUpdatePageSize: handlePageSizeChange
          }"
          flex-height
          class="sm:h-0 sm:flex-1-hidden"
        />
      </div>
    </NCard>

    <ScreenOperateDrawer
      v-model:visible="visible"
      :operate-type="operateType"
      :row-data="editingData"
      @success="getTableData"
    />

    <ScreenDesignerModal
      v-if="designerVisible"
      v-model:visible="designerVisible"
      :screen-id="currentScreenId"
      @success="getTableData"
    />

    <ScreenPreviewModal
      v-if="previewVisible"
      v-model:visible="previewVisible"
      :screen-id="currentScreenId"
    />
  </div>
</template>

<style scoped></style>
